package com.KMGSoftworks.ShoppingList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class CreateListItems extends Activity {
	private final String TAG = "CreateListItems";
	
	private int list_id = 0;
	private String list_name = "";
	private int item_id = 0;
	private int mode = -1;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listitems);
		
		Bundle extras = getIntent().getExtras();
		
		mode = extras.getInt(Constants.MODE);
		list_id = extras.getInt(Constants.ListID);
		list_name = extras.getString(Constants.ListName);
		
		final TextView tv = (TextView) findViewById(R.id.txtListItemName);
		tv.setText(list_name + " Shopping List Items");
		
		final EditText et = (EditText)findViewById(R.id.txtItemName);
/*		
		et.setOnEditorActionListener(new OnEditorActionListener() {
	        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
	            if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
	                InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	                in.hideSoftInputFromWindow(et.getApplicationWindowToken(), 0);
	               //userValidateEntry();
	            }
	            return false;
	        }
	    });
*/
		if(mode == Constants.MODE_EDIT){
			item_id = extras.getInt(Constants.ItemID);
			String itemName = extras.getString(Constants.ItemName);
			int count = extras.getInt(Constants.ListItemCount);

			final NumberPicker np = (NumberPicker)findViewById(R.id.npCount);
			
			et.setText(itemName);
			np.setCurrent(count);
		}

		et.requestFocus();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_create_listitems, menu);
		return true;
	}

	public void handleSaveClick(View view) {
		   	
    	final EditText et = (EditText) findViewById(R.id.txtItemName);
    	final NumberPicker np = (NumberPicker)findViewById(R.id.npCount);
    	
    	int count= np.mCurrent;

        InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
    	
    	String name = et.getText().toString();
    	
    	if(name.length() == 0){
	      	Context context = getApplicationContext();
	    	CharSequence text = "Item name is required!";
	
	    	Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
	    	toast.setGravity(Gravity.TOP, 0, 30);
	    	toast.show();	
    	}
    	else {
    		ContentValues values = new ContentValues(); 
			values.put(ShoppingList.ListItem.COLUMN_NAME_ITEM_ID, name);
			values.put(ShoppingList.ListItem.COLUMN_NAME_COUNT, count);
			values.put(ShoppingList.ListItem.COLUMN_NAME_LIST_ID, list_id);

    		switch(mode){
    			case Constants.MODE_EDIT:
    				Uri itemUri = ContentUris.withAppendedId(ShoppingList.Item.CONTENT_ID_URI_PATTERN, item_id);
    				getContentResolver().update(itemUri, values, null, null);
					Log.i(TAG, "update - " + itemUri.toString());
					this.finish();
    				break;
    			default:
    				if(ItemExists(name) == false){
    					Uri uri = getContentResolver().insert(ShoppingList.ListItem.CONTENT_URI, values);
    					Log.i(TAG, "insert - " + uri.toString());
    					updateListCount();
    				}
    				else{
    		  			AlertDialog alert = new AlertDialog.Builder(this).create();
    	    			alert.setTitle("Add New List");
    	    			alert.setMessage(name + " already exists! Add canceled.");
    	       			alert.setButton("Ok", new DialogInterface.OnClickListener() {
    	    			      public void onClick(DialogInterface dialog, int which) {
    	    			        return;
    	    			    }}); 

    	    			alert.show();
    				}
    				break;
    		}
    	}
    	et.setText("");
    	np.changeCurrent(0);
    	
    	et.requestFocus();
    }
	      
	private boolean ItemExists(String itemName) {
    	String[] args = new String[] {itemName};
    	Cursor c = getContentResolver().query(
    			ShoppingList.Item.CONTENT_URI, 
    			null, 
    			ShoppingList.Item.SELECTION, 
    			args, 
    			null);
    	
    	return c != null && c.getCount() > 0;
    	
	}

    private void updateListCount() {
    	
       	Cursor c = getContentResolver().query(
    			ShoppingList.List.CONTENT_URI, 
    			ShoppingList.List.LIST_PROJECTION, 
    			ShoppingList.List.SELECTION,
    			new String[] { list_name }, 
    			ShoppingList.List.DEFAULT_SORT_ORDER);

       	if(c != null && c.getCount() > 0 && c.getColumnIndex(ShoppingList.List.COLUMN_NAME_COUNT)> -1){
       		c.moveToFirst();
      		int count = c.getInt(ShoppingList.List.COLUMN_INDEX_COUNT);
      		int rowID = c.getInt(0);
      		count++;
      		
      		ContentValues values = new ContentValues();
      		values.put(ShoppingList.List.COLUMN_NAME_COUNT, count);
      		
      		Uri listUri = ContentUris.withAppendedId(ShoppingList.List.CONTENT_ID_URI_PATTERN, rowID);
      		getContentResolver().update(listUri, values, null, null);
       	}
	}

	

}
